package com.jing.cloud.service.config;


import com.alibaba.fastjson.serializer.SerializeConfig;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.alibaba.fastjson.serializer.ToStringSerializer;
import com.alibaba.fastjson.support.config.FastJsonConfig;
import com.alibaba.fastjson.support.spring.FastJsonHttpMessageConverter4;
import org.springframework.boot.autoconfigure.web.HttpMessageConverters;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.nio.charset.Charset;


@Configuration
public class MessageConverterConfig {
    /**
     * fastJson序列化配置
     */
    public static final FastJsonConfig FAST_JSON_CONFIG = new FastJsonConfig();

    static {
        FAST_JSON_CONFIG.setSerializerFeatures(
//                SerializerFeature.PrettyFormat
                SerializerFeature.DisableCircularReferenceDetect
                , SerializerFeature.WriteNullNumberAsZero
                , SerializerFeature.SortField
                , SerializerFeature.WriteMapNullValue
                , SerializerFeature.WriteNullListAsEmpty
                , SerializerFeature.WriteNullStringAsEmpty);
        FAST_JSON_CONFIG.setDateFormat("yyyy-MM-dd HH:mm:ss");
        SerializeConfig serializeConfig = new SerializeConfig();
        //long太长，js精度丢在，转成string输出
        serializeConfig.put(Long.class, ToStringSerializer.instance);
        FAST_JSON_CONFIG.setSerializeConfig(serializeConfig);
        FAST_JSON_CONFIG.setCharset(Charset.forName("utf-8"));
    }

    /**
     * 使用fastJson
     *
     * @return
     */
    @Bean
    public HttpMessageConverters fastJsonHttpMessageConverters() {

        FastJsonHttpMessageConverter4 fastConverter = new FastJsonHttpMessageConverter4();
        //序列化配置
        fastConverter.setFastJsonConfig(FAST_JSON_CONFIG);

        return new HttpMessageConverters(fastConverter);
    }
}
